<template>
  <div class="address-container">
    <PageHeader title="地址管理" />
    <!-- 添加地址表单 -->
    <div class="form-container">
      <Form @submit="saveAddress">
        <!-- 地图组件 -->
        <div class="map-wrapper">
          <Map
            ref="mapRef"
            :show-search="true"
            :show-coordinates="true"
            :map-height="'300px'"
            @location-updated="handleLocationUpdated"
            @location-clicked="handleLocationClicked"
          />
        </div>

        
        <Field
          v-model="addressForm.detailAddress"
          label="打卡地址"
          required
          placeholder="请输入详细地址"
          type="textarea"
          autosize
        />

        <Field
          v-model="addressForm.describe"
          label="打卡描述"
          type="textarea"
          placeholder="请输入打卡描述"
        />
        
        <!-- 添加经纬度显示 -->
        <div class="coordinates-display" v-if="addressForm.latitude && addressForm.longitude">
          <div class="coordinate-item">
            <span class="coordinate-label">经度:</span>
            <span class="coordinate-value">{{ addressForm.longitude }}</span>
          </div>
          <div class="coordinate-item">
            <span class="coordinate-label">纬度:</span>
            <span class="coordinate-value">{{ addressForm.latitude }}</span>
          </div>
        </div>
        <template v-if="addressForm.latitude && addressForm.longitude">
            当前经纬度：{{ addressForm.latitude }}，{{ addressForm.longitude }}
        </template>
        
        <div class="form-actions">
          <Button round block type="primary" native-type="submit">
            保存
          </Button>
        </div>
      </Form>
    </div>

    <!-- 地址列表 -->
    <PullRefresh v-model="refreshing" @refresh="onRefresh">
      <div class="address-list">
        <div class="list-header">
          <div class="header-left">
            <span class="title">地址列表</span>
            <span v-if="selectedCount > 0" class="selected-count">
              (已选择: {{ selectedCount }})
            </span>
          </div>
          <div class="header-actions">
            <Button 
              size="small" 
              type="primary" 
              plain
              @click="handleSelectAll"
            >
              {{ isAllSelected ? '取消全选' : '全选' }}
            </Button>
            <Button 
              v-if="selectedCount > 0"
              size="small" 
              type="danger" 
              @click="deleteSelected"
            >
              删除选中
            </Button>
          </div>
        </div>
        
        <div v-if="paginatedAddressList.length > 0">
          <div 
            v-for="(item, index) in paginatedAddressList"
            :key="item.id" 
            class="address-card"
          >
            <div class="address-checkbox">
              <Checkbox v-model="selectedItems[item.id]" />
            </div>
            <div class="address-index">{{ (currentPage - 1) * pageSize + index + 1 }}.</div>
            <div class="address-info">
              <div class="address-title">{{ item.address }}</div>
              <div class="address">{{ item.describe }}</div>
              <div class="address">{{ item.created_at }}</div>
            </div>
            <div class="address-actions">
              <Button size="small" type="danger" @click="deleteAddress(item.id)">删除</Button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-tip">
          暂无地址
        </div>

        <!-- 分页组件 -->
        <div class="pagination-wrapper" v-if="total > 0">
          <Pagination
            :current-page="currentPage"
            :total-pages="totalPages"
            :total="total"
            @page-change="handlePageChange"
          />
        </div>
      </div>
    </PullRefresh>
  </div>
</template>

<script setup>
import PageHeader from '@/Pages/compontents/PageHeader.vue';
import { ref, reactive, onMounted, computed } from 'vue';
import { Form, Field, Button, showToast, showConfirmDialog, PullRefresh, Checkbox, Cell } from 'vant';
import Pagination from '@/Pages/compontents/Pagination.vue';
import Map from '@/Pages/compontents/Map.vue';
import apiUrls from '@/config/apiUrls'; 
import request from '@/utils/request';
import { data } from 'autoprefixer';
// 下拉刷新状态
const refreshing = ref(false);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const addressList = ref([]);

// 地址表单数据
const addressForm = reactive({
  detailAddress: '',
  describe: '',
  latitude: '',
  longitude: ''
});

// 地图相关
const mapRef = ref(null);

// 选择相关
const selectedItems = ref({});
const isAllSelected = ref(false);

// 计算当前页显示的地址列表
const paginatedAddressList = computed(() => {
  return addressList.value;
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value);
});

// 计算选中的数量
const selectedCount = computed(() => {
  return Object.values(selectedItems.value).filter(Boolean).length;
});

// 处理页码变化
const handlePageChange = async (page) => {
  currentPage.value = page;
  await refreshList();
};

// 下拉刷新
const onRefresh = async () => {
  try {
    currentPage.value = 1;
    await refreshList();
    showToast('刷新成功');
  } catch (error) {
    showToast('刷新失败');
  } finally {
    refreshing.value = false;
  }
};

// 刷新列表
const refreshList = async () => {
  try {
    const response = await request.get(apiUrls.address.addressList, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    
    if (response.code === 200) {
      addressList.value = response.data.list || [];
      total.value = parseInt(response.data.total) || 0;
      
      // 如果当前页没有数据且不是第一页，则返回第一页
      if (addressList.value.length === 0 && currentPage.value > 1) {
        currentPage.value = 1;
        await refreshList();
      }
    }
  } catch (error) {
    showToast('获取数据失败');
    console.error('获取数据失败:', error);
  }
};

// 保存地址
const saveAddress = async () => {
  try {
    // 验证表单
    if (!addressForm.detailAddress.trim()) {
      return;
    }

    const response = await request.post(apiUrls.address.addressList, {
      address: addressForm.detailAddress,
      describe: addressForm.describe
    });
    
    if (response.code === 200) {
      showToast(response.message);
      // 清空表单
      addressForm.detailAddress = '';
      addressForm.describe = '';
      // 刷新列表
      refreshList();
    }
  } catch (error) {
    showToast(error.message || '保存失败');
  }
};

// 删除地址
const deleteAddress = async (id) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这个地址吗？',
    });
    
    const response = await request.delete(`${apiUrls.address.addressList}`, {
      data: {
        ids: [id]
      }
    });
    if (response.code === 200) {
      showToast('删除成功');
      refreshList();
    }
  } catch (error) {
    // 用户取消删除
  }
};

// 处理位置更新事件
const handleLocationUpdated = (location) => {
    console.log('位置已更新:', location);
};

// 处理位置点击事件
const handleLocationClicked = (location) => {
    console.log('位置已点击:', location);
    
    if (!location || typeof location.lng !== 'number' || typeof location.lat !== 'number') {
        console.error('无效的位置数据:', location);
        return;
    }
    
    if (location.name && location.address) {
      addressForm.detailAddress = location.address;
    } else {
        if (mapRef.value) {
            mapRef.value.geocodeLocation(Number(location.lng), Number(location.lat))
                .then(result => {
                    if (result) {
                        addressForm.detailAddress = result.address;
                        addressForm.latitude = location.lat;
                        addressForm.longitude = location.lng;
                    }
                })
                .catch(error => {
                  showToast(error);
                });
        }
    }
};

// 处理全选
const handleSelectAll = () => {
  isAllSelected.value = !isAllSelected.value;
  paginatedAddressList.value.forEach((item) => {
    selectedItems.value[item.id] = isAllSelected.value;
  });
};

// 删除选中的地址
const deleteSelected = async () => {
  const selectedIds = Object.entries(selectedItems.value)
    .filter(([_, value]) => value)
    .map(([key]) => key);

  if (selectedIds.length === 0) {
    showToast('请选择要删除的地址');
    return;
  }

  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除选中的 ${selectedIds.length} 个地址吗？`,
    });
    
    const response = await request.delete(apiUrls.address.addressList, {
      data: {
        ids: selectedIds
      }
    });
    
    if (response.code === 200) {
      showToast('删除成功');
      selectedItems.value = {};
      isAllSelected.value = false;
      refreshList();
    }
  } catch (error) {
    // 用户取消删除或删除失败
    if (error.message) {
      showToast(error.message);
    }
  }
};

// 组件挂载时获取地址列表
onMounted(() => {
  refreshList();
});
</script>

<style scoped>
.address-container {

  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-container {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.address-list {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 4px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.selected-count {
  color: #1989fa;
  font-size: 14px;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.address-card {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.address-checkbox {
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.address-index {
  margin-right: 12px;
  color: #999;
  font-size: 14px;
}

.address-info {
  flex: 1;
  overflow: hidden;
}

.address-title {
  font-size: 15px;
  color: #323233;
  margin-bottom: 4px;
}

.address {
  font-size: 13px;
  color: #666;
  margin-top: 4px;
}

.address-actions {
  margin-left: 12px;
}

.empty-tip {
  text-align: center;
  color: #969799;
  padding: 32px 0;
}

.form-actions {
  margin-top: 24px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.pagination-buttons {
  display: flex;
  gap: 10px;
}

.map-wrapper {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.coordinates-display {
  margin: 8px 16px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.coordinate-item {
  display: flex;
  align-items: center;
  margin: 4px 0;
}

.coordinate-label {
  color: #666;
  margin-right: 8px;
  width: 40px;
}

.coordinate-value {
  color: #333;
  font-family: monospace;
}
</style>